import pandas as pd
import numpy as np


def KDJ(data,window = 9):
    #倒置数据,但不应该是这里做的,
    # data =data.reset_index()
    # del data['index']
    highest = data['high'].rolling(window=window).apply(max)
    highest.fillna(value = data['high'].expanding().max(),inplace=True)

    lowest = data['low'].rolling(window=window).apply(min)
    lowest.fillna(value = data['low'].expanding().min(),inplace=True)
    rsv = (data.close-lowest)/(highest-lowest)*100
    #用100填充空值
    rsv.fillna(value=100.00,inplace = True)
    #分别计算kdj
    data['k'] = rsv.ewm(com=2,adjust =False).mean()
    data['d'] = data['k'].ewm(com=2,adjust =False).mean()
    data['j'] = 3*data['k']-2*data['d']

#不林线
def BOLL(data):
    n = 100
    m = 2
    # 计算均线
    data['median'] = data['close'].rolling(n, min_periods=1).mean()
    # 计算上轨、下轨道
    data['std'] = data['close'].rolling(n, min_periods=1).std(ddof=0)  # ddof代表标准差自由度
    data['upper'] = data['median'] + m * data['std']
    data['lower'] = data['median'] - m * data['std']

#的到N日的移动平均线
#dfmn原始数据
#key某个列
#n原来的数据
def MACD(dfMn,key,n):
    dfn = dfMn[key].rolling(n,closed='right').mean()
    dfMn = dfMn.insert(1,'M'+str(n),dfn)

# 默认时间跨度设为6天
def RSI(data,period = 6):
    print("kaishi")
    price = data['close']
    clprcChange = price - price.shift(1)
    clprcChange = clprcChange.dropna()

    indexprc = clprcChange.index
    upPrc = pd.Series(0, index=indexprc)
    upPrc[clprcChange > 0] = clprcChange[clprcChange > 0]

    downPrc = pd.Series(0, index=indexprc)
    downPrc[clprcChange < 0] = -clprcChange[clprcChange < 0]
    risdata = pd.concat([price, clprcChange, upPrc, downPrc], axis=1)
    risdata.columns = ['price', 'PrcChange', 'upPrc', 'downPrc']
    risdata = risdata.dropna()

    SMUP = upPrc.rolling(period).mean().dropna()
    #这里的重置索引，很重要
    SMUP.reset_index(drop=True,inplace=True)

    SMDOWN = downPrc.rolling(period).mean().dropna()
    SMDOWN.reset_index(drop=True,inplace=True)

    rsi = [100 * SMUP[i] / (SMUP[i] + SMDOWN[i]) for i in range(0, len(SMUP))]
    indexRsi = indexprc[(period - 1):]
    rsi = pd.Series(rsi, index=indexRsi)
    data['rsi_6'] = rsi


